<template>
  <div class="payment-view">
    <div class="page-header">
      <h2>确认支付</h2>
      <div class="action-buttons">
        <el-button class="back-button" @click="goBack">
          <el-icon><Back /></el-icon>
          返回修改
        </el-button>
      </div>
    </div>

    <div class="payment-container">
      <!-- 左侧支付信息 -->
      <div class="payment-info-section">
        <el-card class="payment-info-card" shadow="never">
          <div class="payment-amount">
            <div class="amount-label">支付金额</div>
            <div class="amount-value">¥{{ paymentAmount.toFixed(2) }}</div>
          </div>

          <div class="payment-details">
            <div class="detail-item">
              <span class="label">挂号科室:</span>
              <span class="value">{{ appointmentInfo.department }}</span>
            </div>
            <div class="detail-item">
              <span class="label">医生:</span>
              <span class="value">{{ appointmentInfo.doctor }}</span>
            </div>
            <div class="detail-item">
              <span class="label">挂号时间:</span>
              <span class="value">{{ appointmentInfo.time }}</span>
            </div>
            <div class="detail-item">
              <span class="label">支付方式:</span>
              <span class="value">{{ paymentMethodText }}</span>
            </div>
            <div v-if="useInsurance" class="detail-item insurance">
              <span class="label">生育保险:</span>
              <span class="value">已启用</span>
            </div>

            <!-- 新增医保结算信息 -->
            <div
              v-if="paymentMode === 'insurance' && !useInsurance"
              class="insurance-breakdown"
            >
              <div class="breakdown-item">
                <span class="label">原费用:</span>
                <span class="value">¥{{ originalAmount.toFixed(2) }}</span>
              </div>
              <div class="breakdown-item">
                <span class="label">医保报销:</span>
                <span class="value insurance-deduction"
                  >-¥{{ insuranceDeduction.toFixed(2) }}</span
                >
              </div>
              <div class="breakdown-item total">
                <span class="label">实际支付:</span>
                <span class="value total-amount"
                  >¥{{ paymentAmount.toFixed(2) }}</span
                >
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧支付方式选择 -->
      <div class="payment-method-section">
        <el-card shadow="never" class="method-select-card">
          <div class="method-options">
            <div
              v-for="method in availablePaymentMethods"
              :key="method"
              class="method-option"
              :class="{ active: paymentMethod === method }"
              @click="selectPaymentMethod(method)"
            >
              <div class="method-icon">
                <el-icon
                  ><component :is="paymentMethods[method].icon"
                /></el-icon>
              </div>
              <div class="method-text">
                <div class="method-name">{{ paymentMethods[method].name }}</div>
                <div class="method-desc">
                  {{ paymentMethods[method].description }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部支付操作 -->
    <div class="payment-actions">
      <el-button
        type="primary"
        size="large"
        @click="handlePayment"
        :loading="paying"
        class="pay-button"
      >
        <template v-if="!paying">
          <el-icon><Money /></el-icon>
          立即支付 ¥{{ paymentAmount.toFixed(2) }}
        </template>
        <template v-else> 支付中... </template>
      </el-button>

      <div class="security-tips">
        <el-icon><Lock /></el-icon>
        支付安全保证，您的信息不会泄露
      </div>
    </div>

    <!-- 二维码支付弹窗 -->
    <el-dialog
      v-model="showQRCode"
      :title="`${currentMethod.name}支付`"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      center
    >
      <div class="qr-code-dialog">
        <div class="qr-code-mock">
          <div class="qr-code-image">
            <Qrcode :qrUrlStr="qrCodeContent" />
          </div>
          <div class="qr-code-info">
            <p>请使用{{ currentMethod.name }}扫描二维码完成支付</p>
            <p class="amount">支付金额: ¥{{ paymentAmount.toFixed(2) }}</p>
          </div>
        </div>

        <div class="payment-timer">
          <el-progress
            type="circle"
            :percentage="timerPercentage"
            :width="80"
            :color="timerColor"
          >
            <span class="timer-text">{{ countdown }}s</span>
          </el-progress>
          <p class="timer-tip">二维码有效时间</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelPayment">取消支付</el-button>
          <el-button type="primary" @click="refreshQRCode"
            >刷新二维码</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import Qrcode from "@/components/qrcode/Qrcode.vue";
//引入格式化工具
import { PaymentDataFormatter } from "@/utils/paymentDataFormatter";
// 调用后端API接口
import { completePayment } from "@/api/api.js";

// 二维码内容
const qrCodeContent = ref("模拟支付");

const props = defineProps({
  appointmentInfo: {
    type: Object,
    required: true,
  },
  paymentMode: {
    type: String,
    required: true,
  },
  useInsurance: {
    type: Boolean,
    default: false,
  },
  // 新增：接收完整的支付数据
  paymentData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["payment-success", "payment-failed", "back"]);

const paying = ref(false);
const showQRCode = ref(false);
const paymentMethod = ref("alipay");
const countdown = ref(180); // 3分钟倒计时
const timer = ref(null);

// 支付方式映射
const paymentMethods = {
  alipay: { name: "支付宝", icon: "Iphone", description: "推荐使用，快速安全" },
  wechat: { name: "微信支付", icon: "Iphone", description: "便捷支付方式" },
  digital: { name: "数字人民币", icon: "Money", description: "新型支付方式" },
  // medical: { name: '职工医保', icon: 'User', description: '医保个人账户支付' }
};

// 计算可用的支付方式
const availablePaymentMethods = computed(() => {
  if (props.paymentMode === "insurance") {
    // 医保支付模式下，只显示医保支付方式
    return ["alipay", "wechat", "digital"];
  } else {
    // 自费支付模式下，显示所有支付方式
    return ["alipay", "wechat", "digital"];
  }
});

// 添加计算属性来获取实际的医保报销金额
const actualInsuranceDeduction = computed(() => {
  // 优先使用 paymentData 中的医保报销金额
  if (props.paymentData.paymentInfo?.insuranceDeduction) {
    return props.paymentData.paymentInfo.insuranceDeduction;
  }

  // 如果没有，使用本地计算的值
  if (props.paymentMode === "insurance" && !props.useInsurance) {
    const deduction = originalAmount.value * 0.55;
    return Math.round(deduction * 100) / 100;
  }
  return 0;
});

const currentMethod = computed(() => {
  return paymentMethods[paymentMethod.value] || paymentMethods.alipay;
});

const paymentMethodText = computed(() => {
  return currentMethod.value.name;
});

// 原始费用
const originalAmount = computed(() => {
  return props.appointmentInfo.fee || 0;
});

// 医保报销金额（55%报销比例）
const insuranceDeduction = computed(() => {
  if (props.paymentMode === "insurance" && !props.useInsurance) {
    const deduction = originalAmount.value * 0.55;
    return Math.round(deduction * 100) / 100; // 保留两位小数
  }
  return 0;
});

// 实际支付金额
const paymentAmount = computed(() => {
  // 如果有生育保险，费用为0
  if (props.useInsurance && props.paymentMode === "insurance") {
    return 0;
  }

  // 如果是医保支付，扣除报销部分
  if (props.paymentMode === "insurance") {
    const amount = Math.max(0, originalAmount.value - insuranceDeduction.value);
    return Math.round(amount * 100) / 100; // 保留两位小数
  }

  // 自费支付，全额支付
  return Math.round(originalAmount.value * 100) / 100; // 保留两位小数
});

const timerPercentage = computed(() => {
  return Math.round((countdown.value / 180) * 100);
});

const timerColor = computed(() => {
  if (countdown.value > 60) return "#67C23A";
  if (countdown.value > 30) return "#E6A23C";
  return "#F56C6C";
});

const selectPaymentMethod = (method) => {
  paymentMethod.value = method;
};

const refreshQRCode = () => {
  // 重置倒计时
  countdown.value = 180;
  // 这里可以添加刷新二维码的逻辑
  ElMessage.success("二维码已刷新");
};

const startTimer = () => {
  clearInterval(timer.value);
  countdown.value = 180;
  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer.value);
      ElMessage.warning("二维码已过期，请刷新");
    }
  }, 1000);
};

const cancelPayment = () => {
  clearInterval(timer.value);
  showQRCode.value = false;
  paying.value = false;
};

// 处理支付逻辑
const handlePayment = async () => {
  try {
    paying.value = true;
    
    // 格式化数据为后端需要的结构
    const formattedData = PaymentDataFormatter.formatToBackend(props.paymentData);
    console.log('提交的支付数据:', formattedData);

    // 如果是医保支付且金额为0，直接完成
    if (paymentAmount.value === 0) {
      console.log("处理零金额支付");
      
      const response = await completePayment(formattedData);
      console.log('支付响应:', response);

      if (response && response.code === 200) {
        ElMessage.success("支付成功，挂号完成");
        emit("payment-success", {
          amount: paymentAmount.value,
          method: paymentMethod.value,
          appointmentId: props.paymentData.appointmentId,
          paymentData: props.paymentData,
          insuranceDeduction: actualInsuranceDeduction.value,
        });
      } else {
        throw new Error(response?.message || '支付失败');
      }
      return;
    }

    // 非零金额支付，显示二维码
    showQRCode.value = true;
    startTimer();

    // 模拟扫码支付过程
    setTimeout(async () => {
      try {
        const response = await completePayment(formattedData);
        console.log('支付响应:', response);

        if (response && response.code === 200) {
          clearInterval(timer.value);
          ElMessage.success("支付成功，挂号完成");
          emit("payment-success", {
            amount: paymentAmount.value,
            method: paymentMethod.value,
            appointmentId: props.paymentData.appointmentId,
            paymentData: props.paymentData,
            insuranceDeduction: actualInsuranceDeduction.value,
          });
        } else {
          throw new Error(response?.message || '支付失败');
        }
      } catch (error) {
        console.error("支付失败:", error);
        ElMessage.error(error.message || "支付失败，请稍后重试");
        emit("payment-failed", {
          amount: paymentAmount.value,
          method: paymentMethod.value,
          errorCode: "PAYMENT_FAILED",
        });
      } finally {
        paying.value = false;
        showQRCode.value = false;
      }
    }, 3000); // 模拟3秒支付过程

  } catch (error) {
    console.error("支付处理错误:", error);
    ElMessage.error(error.message || "支付处理失败");
    paying.value = false;
    showQRCode.value = false;
  }
};

const goBack = () => {
  emit("back");
};

// 生成挂号编号
const generateAppointmentId = () => {
  const now = new Date();
  const year = now.getFullYear().toString(); // 年份四位
  const month = (now.getMonth() + 1).toString().padStart(2, "0"); // 月份
  const day = now.getDate().toString().padStart(2, "0"); // 日期
  const dateStr = year + month + day; // 年月日

  // 生成6位随机数
  const randomNum = Math.floor(100000 + Math.random() * 900000).toString();

  return `TJ${dateStr}${randomNum}`;
};

onMounted(() => {
  // 根据支付模式设置默认支付方式
  if (props.paymentMode === "insurance") {
    paymentMethod.value = "medical";
  } else {
    paymentMethod.value = "alipay";
  }
});

onUnmounted(() => {
  clearInterval(timer.value);
});
</script>

<style lang="scss" scoped>
.payment-view {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;

  h2 {
    margin: 0;
    color: #303133;
    font-size: 28px;
    font-weight: 600;
  }
}

.payment-container {
  display: flex;
  gap: 24px;
  margin-bottom: 32px;

  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.payment-info-section {
  flex: 1;
  min-width: 0;
}

.payment-method-section {
  flex: 1;
  min-width: 0;
}

.payment-info-card {
  height: 100%;
  border: 1px solid #e6f3ff;
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
  border-radius: 12px;

  :deep(.el-card__body) {
    padding: 24px;
  }
}

.payment-amount {
  text-align: center;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #dbeafe;

  .amount-label {
    font-size: 16px;
    color: #606266;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .amount-value {
    font-size: 36px;
    font-weight: bold;
    color: #f56c6c;
  }
}

.payment-details {
  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #dbeafe;

    &:last-child {
      border-bottom: none;
    }

    .label {
      color: #606266;
      font-weight: 500;
      font-size: 14px;
    }

    .value {
      color: #303133;
      font-weight: 600;
      font-size: 14px;
    }

    &.insurance {
      .value {
        color: #67c23a;
      }
    }
  }
}

.insurance-breakdown {
  margin-top: 16px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  border: 1px solid #dbeafe;

  .breakdown-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;

    .label {
      color: #606266;
      font-weight: 500;
      font-size: 14px;
    }

    .value {
      color: #303133;
      font-weight: 600;
      font-size: 14px;

      &.insurance-deduction {
        color: #67c23a;
      }

      &.total-amount {
        color: #f56c6c;
        font-size: 16px;
      }
    }

    &.total {
      border-top: 1px solid #dbeafe;
      margin-top: 8px;
      padding-top: 12px;
    }
  }
}

.method-select-card {
  border-radius: 12px;
  border: 1px solid #f0f0f0;

  :deep(.el-card__body) {
    padding: 0;
  }
}

.method-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 20px;
}

.method-option {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid #f0f0f0;
  background: white;

  &:hover {
    border-color: #3b82f6;
    background: #f8fafc;
    transform: translateY(-1px);
  }

  &.active {
    border-color: #3b82f6;
    background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
  }
}

.method-icon {
  width: 44px;
  height: 44px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  flex-shrink: 0;

  .el-icon {
    font-size: 20px;
    color: white;
  }
}

.method-text {
  flex: 1;
  min-width: 0;

  .method-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
  }

  .method-desc {
    font-size: 13px;
    color: #909399;
  }
}

.payment-actions {
  text-align: center;
  margin-top: 32px;

  .pay-button {
    width: 100%;
    max-width: 400px;
    height: 60px;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;
    border-radius: 12px;
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;

    &:hover:not(:disabled) {
      background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(59, 130, 246, 0.3);
    }

    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
      transform: none;
    }

    .el-icon {
      margin-right: 8px;
    }
  }

  .security-tips {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: #67c23a;
    font-size: 14px;
    font-weight: 500;
  }
}

.back-button {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  color: #475569;
  border: 1px solid #cbd5e1;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;

  &:hover {
    background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
    transform: translateY(-1px);
  }
}

/* 二维码弹窗样式 */
.qr-code-dialog {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
}

.qr-code-mock {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.qr-code-image {
  width: 220px;
  height: 220px;
  background-color: #f8fafc;
  border: 2px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  border-radius: 8px;
  padding: 10px;
  box-sizing: border-box;
}

.qr-code-info {
  text-align: center;

  p {
    margin: 8px 0;
    color: #606266;

    &.amount {
      font-weight: bold;
      color: #f56c6c;
      font-size: 18px;
    }
  }
}

.payment-timer {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;

  .timer-text {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
  }

  .timer-tip {
    margin-top: 8px;
    color: #909399;
    font-size: 14px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
}

@media (max-width: 768px) {
  .payment-view {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 20px;

    h2 {
      font-size: 24px;
    }
  }

  .payment-info-card {
    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .payment-amount {
    .amount-value {
      font-size: 32px;
    }
  }

  .method-option {
    padding: 14px;
  }

  .method-icon {
    width: 40px;
    height: 40px;

    .el-icon {
      font-size: 18px;
    }
  }

  .pay-button {
    height: 56px;
    font-size: 16px;
  }

  .qr-code-image {
    width: 200px;
    height: 200px;
  }

  :deep(.el-dialog) {
    width: 90% !important;
    max-width: 400px;
  }
}

@media (max-width: 480px) {
  .payment-view {
    padding: 12px;
  }

  .page-header {
    h2 {
      font-size: 22px;
    }
  }

  .payment-container {
    gap: 16px;
  }

  .method-options {
    padding: 16px;
    gap: 10px;
  }

  .method-option {
    padding: 12px;
  }

  .method-text {
    .method-name {
      font-size: 15px;
    }

    .method-desc {
      font-size: 12px;
    }
  }
}
</style>
[file content end]